package cn.wing.saveddata;

import cn.wing.constant.GuiConstant;
import cn.wing.utils.TransactionInfo;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.saveddata.SavedData;
import net.minecraft.world.level.storage.DimensionDataStorage;
import org.jetbrains.annotations.NotNull;

public class TransactionInfoData extends SavedData {
    private static final String TRANSACTION_INFO_DATA_NAME = "transaction_info_data_name";

    /* ---------- 工具构造 ---------- */
    public TransactionInfoData() { }

    public static TransactionInfoData get(Level level) {
        if (!(level instanceof ServerLevel serverLevel))
            throw new IllegalStateException("只能在服务端调用");

        DimensionDataStorage storage = serverLevel.getDataStorage();
        return storage.computeIfAbsent(
                nbt -> {
                    GuiConstant.TRANSACTION_INFO_MAP.clear();
                    TransactionInfoData d = new TransactionInfoData();
                    d.load(nbt);
                    return d;
                },
                TransactionInfoData::new,
                TRANSACTION_INFO_DATA_NAME
        );
    }


    /* ---------- 存档读写 ---------- */
    @Override
    public @NotNull CompoundTag save(@NotNull CompoundTag tag) {
        ListTag list = new ListTag();
        GuiConstant.TRANSACTION_INFO_MAP.forEach((k, v) -> {
            CompoundTag save = TransactionInfo.save(v);
            list.add(save);
        });
        tag.put(TRANSACTION_INFO_DATA_NAME, list);
        return tag;
    }

    private void load(CompoundTag tag) {
        ListTag list = tag.getList(TRANSACTION_INFO_DATA_NAME, Tag.TAG_COMPOUND);
        for (int i = 0; i < list.size(); i++) {
            CompoundTag itemTag = list.getCompound(i);
            TransactionInfo tarTransactionInfo = TransactionInfo.load(itemTag);
            GuiConstant.TRANSACTION_INFO_MAP.put(tarTransactionInfo.getUuid(), tarTransactionInfo);
        }
    }

}
